package com.chenyaohua.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FileUtils {

    public static void copys (String source,String target) {
        Path sourcePath = Paths.get(source);
        Path targetPath = Paths.get(target);
        Path parent = targetPath.getParent();

        try {

            if (!Files.exists(sourcePath)) {
                //如果不存在
                return;
            }

            if (!Files.exists(parent)) {
                //如果不存在创建该文件的父文件夹
                Files.createDirectories(parent);
            }


            if (!sourcePath.toFile().isDirectory()) {
                //如果不是一个文件夹就创建或替换文件
                Files.copy(sourcePath,targetPath,StandardCopyOption.REPLACE_EXISTING);
                return ;
            }else{

                if (Files.exists(targetPath)) {
                    //如果文件夹存在就删除文件夹
                    Files.walkFileTree(targetPath,new DeleteSimpleFileVisitor());

                }
                //创建文件夹
                Files.createDirectories(targetPath);
            }

            Files.walkFileTree(sourcePath, new CopySimpleFileVisitor(sourcePath,targetPath));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
